package com.example.resourceSharingPlatform.dao;

import com.example.resourceSharingPlatform.entity.Account;
import com.example.resourceSharingPlatform.mappers.AccountRowMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

@Service
public class AccountDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 根据id查询account信息
     * parameter: int id
     * */
    public Account queryAccountById(String id){
        String sql = "SELECT * FROM account WHERE user_id=?";
        Account account = jdbcTemplate.queryForObject(sql, new AccountRowMapper(), id);
        return account;
    }

    /**
     * 插入一条account信息
     * parameter: Account account
     * */
    public Account insertAccount(Account account){
        String sql = "INSERT INTO account VALUES(?,?,?)";
        jdbcTemplate.update(sql, account.getId(), account.getBalance(), account.getCredit());
        String sql2 = "SELECT * FROM account WHERE user_id=?";
        return jdbcTemplate.queryForObject(sql2, new AccountRowMapper(), account.getId());
    }

    /**
     * 根据id 更新一条account信息
     */
    public boolean updateAccount(Account account){
        String sql = "UPDATE account SET balance=?, credit=? WHERE user_id="+account.getId();
        int row = jdbcTemplate.update(sql, new AccountRowMapper(),
                account.getBalance(), account.getCredit());
        return row != 0;
    }

    /**
     * 根据id删除一条account信息
     * */
    public boolean deleteAccount(String id){
        String sql = "DELETE FROM account WHERE user_id=?";
        int row = jdbcTemplate.update(sql, id);
        return row != 0;
    }

}
